package com.hshit.downloader.services;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.http.client.ClientProtocolException;

import android.os.AsyncTask;

import com.hshit.downloader.models.TrackInfo;
import com.hshit.downloader.utils.Utility;

public class Mp3Service extends AsyncTask<String, Void, List<TrackInfo>>{
	private String keyword;
	
	private NetworkAsyncCallback<List<TrackInfo>> callback;
	
	private TrackAction trackAction;
	
	public Mp3Service(String keyword, NetworkAsyncCallback<List<TrackInfo>> callback) {
		setCallback(callback);
		setKeyword(keyword);
	}
	
	Exception e;
	@Override
	protected List<TrackInfo> doInBackground(String... params) {
		List<TrackInfo> tracks = null;
		InputStream in = null;
		try {
			trackAction = new TrackAction(Utility.getFromID(1));
			tracks = trackAction.searchTracks(params[0]);
		} catch (ClientProtocolException e) {
			this.e = e;
			return tracks;
		} catch (IOException e) {
			this.e = e;
			return tracks;
		} catch (Exception e) {
			this.e = e;
			return tracks;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}
		return tracks;
	}
	
	@Override
	protected void onPostExecute(List<TrackInfo> mResult) {
		if (!mResult.equals("")) {
			if (getCallback() != null) getCallback().onSuccess(keyword, mResult);
		} else {
			if (getCallback() != null) getCallback().onFailed(keyword, e);
		}
	}
	
	/**
	 * 
	 */
	public void work() {
		execute(getKeyword());
		if (getCallback() != null) getCallback().onStart(keyword);
	}
	
	public NetworkAsyncCallback<List<TrackInfo>> getCallback() {return this.callback; }
	
	public void setCallback(NetworkAsyncCallback<List<TrackInfo>> callback) { this.callback = callback; }
	
	public void setKeyword(String keyword) { this.keyword = keyword; }
	
	public String getKeyword() { return this.keyword; }
	
	/**
	 * @author LONG_KEN
	 */
	
	public static interface NetworkAsyncCallback<T> {
		public void onStart(String mKeyword);
		public void onSuccess(String mKeyword, T response);
		public void onFailed(String mKeyword, Exception e);
	}
}
